package ui;

import cn.hutool.core.io.FileUtil;
import entity.Record;
import entity.User;
import util.*;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.Objects;
import java.util.TreeSet;

import static util.GUIUtil.createButton;

public class UserInfoGUI extends JDialog {
    private Object[][] data;
    private JTable table;
    private JLabel avgStepsLabel;
    private JLabel avgTimeLabel;
    private JLabel minStepsLabel;
    private JLabel minTimeLabel;
    private JLabel avatarLabel;
    private final Window parent;

    public UserInfoGUI(Window parent) {
        this.parent = parent;

        if (parent != null) {
            parent.setVisible(false);
        }
        setTitle("用户数据");
        setSize(710, 600);

        setLocationRelativeTo(null);
        setLayout(new BorderLayout(10, 10));

        // 1. 顶部面板 - 现在包含头像和用户信息
        add(createTopPanel(), BorderLayout.NORTH);

        // 2. 中部面板 - 记录表格
        add(createCenterPanel(), BorderLayout.CENTER);

        // 3. 底部面板 - 统计信息和操作按钮
        add(createBottomPanel(), BorderLayout.SOUTH);

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                dispose();
            }
        });
        setModal(true);
        setVisible(true);
    }

    @Override
    public void dispose() {
        if (parent != null) {
            parent.setVisible(true);
        }
        super.dispose();
    }

    private void loadHistory() {
        User onlineUser = UserManager.getOnlineUser();
        TreeSet<Record> records = onlineUser.getRecords();
        data = new Object[records.size()][3];

        for (int i = 0; i < records.size(); i++) {
            Record record = records.toArray(new Record[0])[i];
            data[i][0] = record.getDateTime();
            data[i][1] = record.getStep();
            data[i][2] = record.getUseTime();
        }
    }

    // 创建顶部面板
    private JPanel createTopPanel() {
        JPanel panel = new JPanel(new BorderLayout(20, 20));
        panel.setBorder(new EmptyBorder(10, 10, 10, 10));

        JPanel leftPanel = new JPanel(new BorderLayout(5, 0));

        User onlineUser = UserManager.getOnlineUser();
        avatarLabel = GUIUtil.createAvatarLabel(onlineUser.getUsername(), 50);
        JLabel userLabel = GUIUtil.createUserLabel(onlineUser, new Font("微软雅黑", Font.BOLD, 16));

        leftPanel.add(avatarLabel, BorderLayout.WEST);
        leftPanel.add(userLabel, BorderLayout.CENTER);

        JPanel rightPanel = getButtonPanel();

        panel.add(leftPanel, BorderLayout.WEST);
        panel.add(rightPanel, BorderLayout.EAST);

        return panel;
    }

    private JPanel getButtonPanel() {
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        // 可配置的按钮列表
        JButton[] buttons = {
                createButton("设置头像", _ -> setAvatar()),
                createButton("退出登录", _ -> logout()),
                createButton("注销账号", _ -> cancelAccount())
        };

        for (JButton button : buttons) {
            buttonPanel.add(button);
        }
        return buttonPanel;
    }

    private void cancelAccount() {
        int i = JOptionPane.showOptionDialog(this, "确定要注销登录吗？这将删除你所有信息", "注销账号",
                JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
                null, new Object[]{"确定", "取消"}, "取消");
        if (i == JOptionPane.YES_OPTION) {
            User onlineUser = UserManager.getOnlineUser();
            UserManager.removeUser(onlineUser);
            UserManager.removeRunData();
            File userDataDir = new File(JsonRW.getStr(JsonRW.configFile, "userDataDir") + "/" + onlineUser.getUsername());
            if (userDataDir.exists()) {
                FileDeal.deleteDirectory(userDataDir);
            }
            parent.dispose();
            this.dispose();
            new LoginGUI();
        }
    }

    private void logout() {
        int i = JOptionPane.showOptionDialog(this, "确定要退出登录吗？", "退出登录",
                JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
                null, new Object[]{"确定", "取消"}, "取消");
        if (i == JOptionPane.YES_OPTION) {
            UserManager.removeRunData();
            parent.dispose();
            this.dispose();
            new LoginGUI();
        }

    }

    private void confirmAndClearRecords(User onlineUser) {
        int i = JOptionPane.showConfirmDialog(this, "确定要清空所有记录吗？", "提示", JOptionPane.YES_NO_OPTION);
        if (i == JOptionPane.YES_OPTION) {
            UserManager.clearRecordsAndSave(onlineUser, this);
        }
    }

    private void setAvatar() {
        GUIUtil.showFileSelectionDialog(this, "选择头像（尽量是方形的）", filePath -> {
            String username = UserManager.getOnlineUser().getUsername();
            String avatarPath = "userData/" + username + "/avatar/0.png";
            System.out.println(avatarPath);
            FileUtil.copy(new File(filePath), new File(avatarPath), true);
            UserManager.saveAvatarToFile(username, avatarPath);
            JOptionPane.showMessageDialog(this, "设置成功！");
            refresh();
        });
    }

    // 创建中部表格面板（保持不变）
    private JPanel createCenterPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.addTab("历史记录", createHistoryPanel());
         tabbedPane.addTab("图片管理", createImageManagementPanel());
         tabbedPane.addTab("设置", createSettingsPanel());
        panel.add(tabbedPane, BorderLayout.CENTER);
        return panel;
    }

    private JPanel createSettingsPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 左侧面板 - 配置项列表
        JPanel leftPanel = new JPanel(new BorderLayout());
        leftPanel.setBorder(BorderFactory.createTitledBorder("配置项"));
        leftPanel.setPreferredSize(new Dimension(150, 0));

        // 将数值配置项整合为一项
        String[] configCategories = {"路径配置", "数值配置"};
        JList<String> categoryList = new JList<>(configCategories);
        categoryList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        categoryList.setSelectedIndex(0);

        // 右侧面板 - 配置详情
        JPanel rightPanel = new JPanel(new BorderLayout());
        rightPanel.setBorder(BorderFactory.createTitledBorder("配置详情"));

        // 创建卡片面板用于切换不同配置项的详情
        JPanel detailPanel = new JPanel(new CardLayout());

        // 路径配置面板
        JPanel pathConfigPanel = createPathConfigPanel();
        detailPanel.add(pathConfigPanel, "路径配置");

        // 数值配置面板
        JPanel numericConfigPanel = createNumericConfigPanel();
        detailPanel.add(numericConfigPanel, "数值配置");

        rightPanel.add(detailPanel, BorderLayout.CENTER);

        // 监听列表选择变化
        categoryList.addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                String selected = categoryList.getSelectedValue();
                CardLayout cl = (CardLayout) (detailPanel.getLayout());
                cl.show(detailPanel, selected);
            }
        });

        JScrollPane listScrollPane = new JScrollPane(categoryList);
        leftPanel.add(listScrollPane, BorderLayout.CENTER);

        panel.add(leftPanel, BorderLayout.WEST);
        panel.add(rightPanel, BorderLayout.CENTER);

        return panel;
    }

    // 创建路径配置面板
    private JPanel createPathConfigPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 路径配置项列表
        String[] pathItems = {"用户数据路径", "运行路径", "默认头像", "默认图片"};
        JList<String> pathList = new JList<>(pathItems);
        pathList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        pathList.setSelectedIndex(0);

        JPanel leftPanel = new JPanel(new BorderLayout());
        leftPanel.setPreferredSize(new Dimension(150, 0));
        leftPanel.add(new JScrollPane(pathList), BorderLayout.CENTER);

        // 路径配置详情面板
        JPanel pathDetailPanel = new JPanel(new CardLayout());

        // 用户数据路径配置面板
        JPanel userDataDirPanel = createConfigDetailPanel("userDataDir", "用户数据存储路径");
        pathDetailPanel.add(userDataDirPanel, "用户数据路径");

        // 运行路径配置面板
        JPanel runPathPanel = createConfigDetailPanel("runPath", "程序运行时数据路径");
        pathDetailPanel.add(runPathPanel, "运行路径");

        // 默认头像配置面板
        JPanel defaultAvatarPanel = createConfigDetailPanel("defaultAvatar", "默认头像路径");
        pathDetailPanel.add(defaultAvatarPanel, "默认头像");

        // 默认图片配置面板
        JPanel defaultImagePanel = createConfigDetailPanel("defaultImage", "默认游戏图片路径");
        pathDetailPanel.add(defaultImagePanel, "默认图片");

        JPanel rightPanel = new JPanel(new BorderLayout());
        rightPanel.add(pathDetailPanel, BorderLayout.CENTER);

        // 监听路径配置项选择变化
        pathList.addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                String selected = pathList.getSelectedValue();
                CardLayout cl = (CardLayout) (pathDetailPanel.getLayout());
                cl.show(pathDetailPanel, selected);
            }
        });

        panel.add(leftPanel, BorderLayout.WEST);
        panel.add(rightPanel, BorderLayout.CENTER);

        return panel;
    }

    // 创建数值配置面板，将所有数值配置项集成在一起
    private JPanel createNumericConfigPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 标题
        JLabel titleLabel = new JLabel("数值配置项");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        titleLabel.setHorizontalAlignment(SwingConstants.CENTER);
        panel.add(titleLabel, BorderLayout.NORTH);

        // 创建带有输入框的表单面板
        JPanel formPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;

        // 图片逆向打乱次数
        gbc.gridx = 0;
        gbc.gridy = 0;
        formPanel.add(new JLabel("图片逆向打乱次数:"), gbc);

        gbc.gridx = 1;
        JTextField disruptStepField = new JTextField(String.valueOf(JsonRW.getInt(JsonRW.configFile, "randomCount")), 15);
        formPanel.add(disruptStepField, gbc);

        gbc.gridx = 2;
        JButton disruptStepButton = getjButton(disruptStepField);
        formPanel.add(disruptStepButton, gbc);

        // 游戏整图宽度
        gbc.gridx = 0;
        gbc.gridy = 1;
        formPanel.add(new JLabel("游戏整图宽度:"), gbc);

        gbc.gridx = 1;
        JTextField widthField = new JTextField(String.valueOf(JsonRW.getInt(JsonRW.configFile, "widthWhole")), 15);
        formPanel.add(widthField, gbc);

        gbc.gridx = 2;
        JButton widthButton = createConfigButton(widthField, "widthWhole");
        formPanel.add(widthButton, gbc);

        // 游戏整图高度
        gbc.gridx = 0;
        gbc.gridy = 2;
        formPanel.add(new JLabel("游戏整图高度:"), gbc);

        gbc.gridx = 1;
        JTextField heightField = new JTextField(String.valueOf(JsonRW.getInt(JsonRW.configFile, "heightWhole")), 15);
        formPanel.add(heightField, gbc);

        gbc.gridx = 2;
        JButton heightButton = createConfigButton(heightField , "heightWhole");
        formPanel.add(heightButton, gbc);

        // 游戏图片行数
        gbc.gridx = 0;
        gbc.gridy = 3;
        formPanel.add(new JLabel("游戏图片行数:"), gbc);

        gbc.gridx = 1;
        JTextField rowsField = new JTextField(String.valueOf(JsonRW.getInt(JsonRW.configFile, "rows")), 15);
        formPanel.add(rowsField, gbc);

        gbc.gridx = 2;
        JButton rowsButton = createConfigButton(rowsField, "rows");
        formPanel.add(rowsButton, gbc);

        // 游戏图片列数
        gbc.gridx = 0;
        gbc.gridy = 4;
        formPanel.add(new JLabel("游戏图片列数:"), gbc);

        gbc.gridx = 1;
        JTextField colsField = new JTextField(String.valueOf(JsonRW.getInt(JsonRW.configFile, "cols")), 15);
        formPanel.add(colsField, gbc);

        gbc.gridx = 2;
        JButton colsButton = createConfigButton(colsField, "cols");
        formPanel.add(colsButton, gbc);

        // 添加一个保存所有配置的按钮
        gbc.gridx = 0;
        gbc.gridy = 5;
        gbc.gridwidth = 3;
        gbc.anchor = GridBagConstraints.CENTER;
        JButton saveAllButton = new JButton("保存所有数值配置");
        saveAllButton.addActionListener(_ -> {
            boolean allValid = true;
            StringBuilder errorMsg = new StringBuilder("以下配置项输入有误:\n");

            try {
                int disruptStep = Integer.parseInt(disruptStepField.getText());
                if (disruptStep <= 0) {
                    allValid = false;
                    errorMsg.append("- 图片逆向打乱次数必须大于0\n");
                } else {
                    JsonRW.set(JsonRW.configFile, "randomCount", disruptStep);
                }
            } catch (NumberFormatException ex) {
                allValid = false;
                errorMsg.append("- 图片逆向打乱次数必须是整数\n");
            }

            try {
                int width = Integer.parseInt(widthField.getText());
                if (width <= 0) {
                    allValid = false;
                    errorMsg.append("- 游戏整图宽度必须大于0\n");
                } else {
                    JsonRW.set(JsonRW.configFile, "widthWhole", width);
                }
            } catch (NumberFormatException ex) {
                allValid = false;
                errorMsg.append("- 游戏整图宽度必须是整数\n");
            }

            try {
                int height = Integer.parseInt(heightField.getText());
                if (height <= 0) {
                    allValid = false;
                    errorMsg.append("- 游戏整图高度必须大于0\n");
                } else {
                    JsonRW.set(JsonRW.configFile, "heightWhole", height);
                }
            } catch (NumberFormatException ex) {
                allValid = false;
                errorMsg.append("- 游戏整图高度必须是整数\n");
            }

            try {
                int rows = Integer.parseInt(rowsField.getText());
                if (rows <= 0) {
                    allValid = false;
                    errorMsg.append("- 游戏图片行数必须大于0\n");
                } else {
                    JsonRW.set(JsonRW.configFile, "rows", rows);
                }
            } catch (NumberFormatException ex) {
                allValid = false;
                errorMsg.append("- 游戏图片行数必须是整数\n");
            }

            try {
                int cols = Integer.parseInt(colsField.getText());
                if (cols <= 0) {
                    allValid = false;
                    errorMsg.append("- 游戏图片列数必须大于0\n");
                } else {
                    JsonRW.set(JsonRW.configFile, "cols", cols);
                }
            } catch (NumberFormatException ex) {
                allValid = false;
                errorMsg.append("- 游戏图片列数必须是整数\n");
            }

            if (allValid) {
                JOptionPane.showMessageDialog(this, "所有数值配置已保存！");
            } else {
                JOptionPane.showMessageDialog(this, errorMsg.toString(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
        formPanel.add(saveAllButton, gbc);

        panel.add(new JScrollPane(formPanel), BorderLayout.CENTER);

        return panel;
    }

    private JButton createConfigButton(JTextField textField, String widthWhole) {
        JButton widthButton = new JButton("修改");
        widthButton.addActionListener(_ -> {
            try {
                int value = Integer.parseInt(textField.getText());
                if (value > 0) {
                    JsonRW.set(JsonRW.configFile, widthWhole, value);
                    JOptionPane.showMessageDialog(this, "设置已保存！");
                } else {
                    JOptionPane.showMessageDialog(this, "请输入大于0的数值！", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "请输入有效的整数！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
        return widthButton;
    }

    private JButton getjButton(JTextField disruptStepField) {
        return createConfigButton(disruptStepField, "randomCount");
    }


    private JPanel createConfigDetailPanel(String configKey, String description) {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 描述标签
        JLabel descLabel = new JLabel(description);
        descLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        panel.add(descLabel, BorderLayout.NORTH);

        // 配置值显示和编辑区域
        JPanel valuePanel = new JPanel(new BorderLayout(5, 5));

        JLabel valueLabel = new JLabel("当前值:");
        String text;
        if (JsonRW.get(JsonRW.configFile, configKey) instanceof String) {
            text = JsonRW.getStr(JsonRW.configFile, configKey);
        } else if (JsonRW.get(JsonRW.configFile, configKey) instanceof Integer) {
            text = String.valueOf(JsonRW.getInt(JsonRW.configFile, configKey));
        } else {
            throw new RuntimeException("未知类型: " + Objects.requireNonNull(JsonRW.get(JsonRW.configFile, configKey)).getClass().getName());
        }
        JTextField valueField = new JTextField(text);
        valueField.setEditable(false);

        JButton editButton = new JButton("修改");
        JButton selectButton = new JButton("选择文件");

        // 根据配置项类型决定是否显示文件选择按钮
        if (configKey.contains("avatar") || configKey.contains("image")) {
            JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
            buttonPanel.add(editButton);
            buttonPanel.add(selectButton);

            selectButton.addActionListener(_ ->
                GUIUtil.showFileSelectionDialog(this, "选择文件", filePath -> {
                    JsonRW.set(JsonRW.configFile, configKey, filePath);
                    valueField.setText(filePath);
                }));
        } else {
            editButton.setText("编辑");
        }

        editButton.addActionListener(_ -> {
            String newValue = JOptionPane.showInputDialog(this,
                    "请输入新的值:", JsonRW.get(JsonRW.configFile, configKey));
            if (newValue != null && !newValue.trim().isEmpty()) {
                if (newValue.matches("\\d+")) {
                    JsonRW.set(JsonRW.configFile, configKey, Integer.parseInt(newValue));
                } else {
                    JsonRW.set(JsonRW.configFile, configKey, newValue);
                }
                valueField.setText(newValue);
            }
        });

        valuePanel.add(valueLabel, BorderLayout.WEST);
        valuePanel.add(valueField, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        buttonPanel.add(editButton);
        if (configKey.contains("avatar") || configKey.contains("image")) {
            buttonPanel.add(selectButton);
        }

        valuePanel.add(buttonPanel, BorderLayout.SOUTH);

        panel.add(valuePanel, BorderLayout.CENTER);

        // 显示配置键名
        JLabel keyLabel = new JLabel("配置键: " + configKey);
        keyLabel.setFont(new Font("微软雅黑", Font.ITALIC, 12));
        keyLabel.setForeground(Color.GRAY);
        panel.add(keyLabel, BorderLayout.SOUTH);

        return panel;
    }

    private JPanel createHistoryPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        JPanel mainPanel = new JPanel(new BorderLayout());
        String[] columns = {"记录时间", "步数", "用时(秒)"};
        loadHistory();
        DefaultTableModel model = new DefaultTableModel(data, columns) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        table = new JTable(model);
        table.setRowHeight(30);
        table.setFont(new Font("微软雅黑", Font.PLAIN, 14));

        // 设置表头样式
        JTableHeader header = table.getTableHeader();
        header.setFont(new Font("微软雅黑", Font.BOLD, 15));
        header.setBackground(new Color(120, 120, 120));
        header.setForeground(Color.WHITE);
        header.setReorderingAllowed(false);

        // 设置表格隔行变色
        table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value,
                                                           boolean isSelected, boolean hasFocus,
                                                           int row, int column) {
                Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

                // 设置隔行变色效果
                if (!isSelected) {
                    if (row % 2 == 0) {
                        c.setBackground(Color.WHITE); // 偶数行白色背景
                    } else {
                        c.setBackground(new Color(240, 240, 240)); // 奇数行浅灰色背景
                    }
                }

                // 设置文本居中对齐
                setHorizontalAlignment(JLabel.CENTER);
                return c;
            }
        });

        // 创建一个包含表格和按钮的面板
        JPanel tablePanel = new JPanel(new BorderLayout());

        // 创建清空记录按钮面板并放置在北部（上方）
        JPanel clearButtonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JButton clearButton = new JButton("清空记录");
        clearButton.addActionListener(_ -> confirmAndClearRecords(UserManager.getOnlineUser()));
        clearButtonPanel.add(clearButton);

        // 将按钮面板和表格添加到tablePanel中
        tablePanel.add(clearButtonPanel, BorderLayout.NORTH);
        tablePanel.add(new JScrollPane(table), BorderLayout.CENTER);

        mainPanel.add(tablePanel, BorderLayout.CENTER);

        updateData();

        // 统计信息面板
        JPanel statsPanel = new JPanel(new GridLayout(1, 4, 10, 10));
        statsPanel.setBorder(BorderFactory.createTitledBorder("统计信息"));
        statsPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        Font statsFont = new Font("微软雅黑", Font.BOLD, 14);
        avgStepsLabel.setFont(statsFont);
        avgTimeLabel.setFont(statsFont);
        minStepsLabel.setFont(statsFont);
        minTimeLabel.setFont(statsFont);

        statsPanel.add(avgStepsLabel);
        statsPanel.add(avgTimeLabel);
        statsPanel.add(minStepsLabel);
        statsPanel.add(minTimeLabel);

        mainPanel.add(statsPanel, BorderLayout.SOUTH);

        panel.add(mainPanel, BorderLayout.CENTER);
        return panel;
    }


    private JPanel createImageManagementPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 获取当前用户的图片目录
        User onlineUser = UserManager.getOnlineUser();
        String username = onlineUser.getUsername();
        File imagesDir = new File("userData/" + username + "/images");

        // 如果目录不存在，创建它
        if (!imagesDir.exists()) {
            boolean mkStatus = imagesDir.mkdirs();
            if (!mkStatus) {
                throw new RuntimeException("创建图片目录失败！");
            }
        }

        // 使用ImageManager创建图片管理面板
        JPanel imagePanel = ImageManager.createImagePanel(imagesDir, new Color(240, 240, 240));
        panel.add(imagePanel, BorderLayout.CENTER);

        return panel;
    }

    private JPanel createBottomPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));

        // 只保留操作按钮
        JPanel actionPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton closeButton = new JButton("关闭");
        closeButton.addActionListener(_ -> dispose());
        actionPanel.add(closeButton);

        panel.add(actionPanel, BorderLayout.CENTER);

        return panel;
    }

    public void refresh() {
        User onlineUser = UserManager.getOnlineUser();
        String onlineUsername = onlineUser.getUsername();
        // 刷新头像
        GUIUtil.refreshAvatar(avatarLabel, onlineUsername, 50);
        // 重新加载用户数据
        UserManager.loadUserFromFile();
        // 重新加载历史记录数据
        loadHistory();
        // 更新表格数据
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        // 清空现有数据
        model.setRowCount(0);
        for (Object[] row : data) {
            model.addRow(row);
        }
        updateData();
        revalidate();
        repaint();
    }

    private void updateData() {
        double avgSteps = 0;
        double avgTime = 0;
        int minSteps = 0;
        long minTime = 0;

        TreeSet<Record> records = UserManager.getOnlineUser().getRecords();
        if (records != null && !records.isEmpty()) {
            for (Record record : records) {
                avgSteps += record.getStep();
                avgTime += record.getUseTime();
                minSteps = minSteps == 0 ? record.getStep() : Math.min(minSteps, record.getStep());
                minTime = minTime == 0 ? record.getUseTime() : Math.min(minTime, record.getUseTime());
            }
            int size = records.size();
            avgSteps /= size;
            avgTime /= size;
        } else {
            avgSteps = -1;
            avgTime = -1;
            minSteps = -1;
            minTime = -1;
        }

        avgStepsLabel = new JLabel(String.format("平均步数: %.1f", avgSteps), JLabel.CENTER);
        avgTimeLabel = new JLabel(String.format("平均用时: %.1f秒", avgTime), JLabel.CENTER);
        minStepsLabel = new JLabel("最少步数: " + minSteps, JLabel.CENTER);
        minTimeLabel = new JLabel("最少用时: " + minTime + "秒", JLabel.CENTER);
    }
}
